﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yuchen.NPA.Core;

namespace Yuchen.NPA.EntityFrameworkCore
{
    public static class NPAEFExtension
    {
        public static IServiceCollection ConfigureDbContext<TDbContext>(this IServiceCollection services)
        where TDbContext : DbContext
        {
            //var provider = services.BuildServiceProvider();
            //var dbContext = provider.GetRequiredService<TDbContext>();
            //if (dbContext == null)
            //{
            //    throw new Exception("DbContext必须在此方法前注册");
            //}
            //(dbContext as IAutoConfigureEntities).Configure = (builder) =>
            //{
            //    var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.DefinedTypes)
            //        .Where(x => typeof(INpaRepository<>).IsAssignableFrom(x)).ToList();
            //    foreach (var typeInfo in types)
            //    {
            //        builder.Model.AddEntityType(typeInfo);
            //    }
            //};
            return services;
        }
        public static IServiceCollection AddEntityFrameworkCoreNPA<TRepository, TEntity, TDbContext>(this IServiceCollection services)
        where TEntity : class
        where TRepository : class
        where TDbContext : DbContext
        {
            services.AddNPA<TRepository, TEntity>();
            services.AddScoped<ICommandExecutor<TEntity>, CommandExecutor<TEntity, TDbContext>>();
            return services;
        }
    }
}
